package me.chan.netty.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

@Slf4j
public class HttpProtocolServer {

    public static void main(String[] args) {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG))
                                        .addLast(new HttpServerCodec())
                                        .addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                            @Override
                                            protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                                                if (log.isDebugEnabled()) {
                                                    log.debug("receive from client:\n{}", msg);
                                                }
                                                DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
                                                byte[] resp = "Ok!".getBytes(StandardCharsets.UTF_8);
                                                response.content().writeBytes(resp);
                                                response.headers().setInt(CONTENT_LENGTH, resp.length);
                                                ctx.writeAndFlush(response);
                                            }
                                        });
                        }
                    });
            // waiting for connection established
            ChannelFuture cf = bootstrap.bind(8080).sync();
            // waiting for connection closed
            cf.channel().closeFuture().sync();

        } catch (Exception ex) {

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
